<script lang="ts" setup>
import { reactive, ref } from 'vue'
import * as BasicApi from '@/api'
import { objectToQueryParams } from '@/utils/objectToQuery'
import { useMessage } from '@/hooks/useMessage'
import { Folder, Upload } from '@element-plus/icons-vue'

import * as XLSX from 'xlsx'

const props = defineProps(['type', 'partParams'])

const column = ref<any[]>([])
const tableData = ref<any[]>([])
const outputArray = ref<any[]>([])

const dialogVisible = ref(false)

const open = async () => {
  formInline.fileName = ''
  tableData.value = []
  column.value = []
  outputArray.value = []
  dialogVisible.value = true
}
defineExpose({ open })
const emit = defineEmits(['refresh'])
const message = useMessage()
const onUpload = async () => {
  const inputStr = objectToQueryParams({
    groupName: props.partParams.groupName,
    jobType: props.partParams.jobType,
    operType: 'Upload'
  })
  const result = (await BasicApi.Operate({ inputStr, jsonData: outputArray.value })) as any
  const { code, msg } = result
  if (code !== 200) {
    message.error(msg)
    return
  }
  message.success(msg)
  dialogVisible.value = false
  emit('refresh')
}

const formInline = reactive({
  fileName: ''
})

const fileInput = ref()
const handleFileUpload = (event: any) => {
  const file = event.target.files[0]
  fileInput.value.value = ''
  const reader = new FileReader()
  formInline.fileName = file.name
  reader.onload = (e: any) => {
    const data = new Uint8Array(e.target.result)
    const workbook = XLSX.read(data, { type: 'array' })
    const sheetName = workbook.SheetNames.find((e) => e === 'Sheet1')
    if (sheetName) {
      const worksheet = workbook.Sheets[sheetName]
      tableData.value = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
      // 获取键名
      const keys = tableData.value[0]
      // 生成对象数组
      outputArray.value = tableData.value.slice(1).map((row) => {
        let obj = {}
        row.forEach((value: any, index: number) => {
          obj[keys[index]] = value
        })
        return obj
      })
      let arr = []
      tableData.value[0].forEach((e: any) => {
        arr.push({
          key: e,
          label: e
        })
      })
      column.value = arr
    } else {
      message.error('请检查文件中是否有Sheet1')
    }
  }
  reader.readAsArrayBuffer(file)
}
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    title="上传"
    width="1400"
    :before-close="
      () => {
        dialogVisible = false
      }
    "
  >
    <el-form :inline="true" :model="formInline" class="relative demo-form-inline">
      <el-form-item style="width: 580px" label="File">
        <el-input
          style="width: 320px; margin-right: 10px"
          v-model="formInline.fileName"
          placeholder="请选择文件"
          clearable
        />
        <el-button class="file-button" :icon="Folder" type="success"
          >选择文件<input class="file-input" ref="fileInput" type="file" @change="handleFileUpload"
        /></el-button>
        <el-button :icon="Upload" type="primary" :disabled="!outputArray.length" @click="onUpload">导入</el-button>
      </el-form-item>
      <div class="right-box">
        <p v-if="outputArray.length">
          已导入<span>{{ outputArray.length }}</span
          >条
        </p>
        <p v-else>
          已加载<span>{{ outputArray.length }}</span
          >条
        </p>
      </div>
    </el-form>
    <el-table
      element-loading-text="正在导入数据，请等待..."
      :data="outputArray"
      :header-cell-style="{ background: '#f5f7fa' }"
      border
      stripe
      style="width: 100%"
      height="500"
      highlight-current-row
    >
      <el-table-column
        align="center"
        v-for="(item, index) in column"
        :key="`${item.key}_${index}`"
        :prop="item.key"
        :label="item.label"
        show-overflow-tooltip
      >
        <template #default="scope">
          <span>{{ scope.row[item.key] }}</span>
        </template>
      </el-table-column>
    </el-table>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

.file-button {
  position: relative;
  overflow: hidden;
}
.file-input {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  opacity: 0;
}

.right-box {
  position: absolute;
  top: 5px;
  right: 0;
}
.right-box span {
  color: #ff0000;
}
</style>
